var express = require('express');
var fs = require('fs');
var qr = require('qr-image')
var app = express();
const os = require('os');

function ip() {
    var interfaces = os.networkInterfaces();
    for (var devName in interfaces) {
        var iface = interfaces[devName];
        for (var i = 0; i < iface.length; i++) {
            var alias = iface[i];
            if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
                return alias.address;
            }
        }
    }
}

var ip_addr = ip()
 
function random_port(){
    const port = Math.floor(4096 + Math.random() * 10000)
    var writerStream = fs.createWriteStream('port');
    writerStream.write(port+"",'UTF8');
    writerStream.end();
    return port
}

var port = random_port()

var download_apk_path = '/download/app-release.apk'

app.get(download_apk_path, function (req, res) {
    var filepath = "../app/build/outputs/apk/release/app-release.apk";
    fs.exists(filepath, function(exist) {
        if (!exist) {
            res.send("Not Found");
        } else {
            if (req.headers['range'] == undefined) {
                fs.createReadStream(filepath).pipe(res);
            } else {
                var arg = req.headers['range'].split(",");
                fs.createReadStream(filepath, {start: parseInt(arg[0]), end: parseInt(arg[1])}).pipe(res);
            }
        }
    });
});
app.get('/qrcode.png', function(req, res){
    var text = 'http://' + ip_addr + ':' + port + download_apk_path
    console.info(text)
    var img = qr.image(text,{size :8});
    res.writeHead(200, {'Content-Type': 'image/png'});
    img.pipe(res);
})
 
var server = app.listen(port, function () {
    console.log("listen at " + port);
});
